package msr.frontend;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import msr.object.LoginUser;
import msr.service.UserService;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("logged")
public class LoginController {
	private String username;
	private String passwd;
	private UserService uService = new UserService();

	/**
	 * login execute
	 * 
	 * @author tuvv
	 * @param username
	 * @param passwd
	 * @return message that view in client
	 * */

	@RequestMapping("/login.htm")
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		username = request.getParameter("username");
		passwd = request.getParameter("passwd");
		boolean check = uService.checkLogin(username, passwd);

		LoginUser loginUser = new LoginUser(username, passwd);
		// ValidatorFactory vFactory = new ValidatorFactory();
		// ExpertValidator validator = vFactory
		// .getValidator(RequestAction.VALIDATOR_USER);
		// validator.validate(loginUser, errors);
		System.out.println("value of check " + check);
		ModelAndView mav = new ModelAndView();
		if (check) {
			// add into session
			String passMd5 = DigestUtils.md5Hex(this.passwd);
			System.out.println("value of username " + username);
			mav.addObject("username", this.username);
			mav.addObject("passwd", passMd5);
			mav.addObject("logged", true);
			mav.setViewName("welcome");
		} else {
			// addActionError(getText("error.login"));
			mav.addObject("logged", false);
			mav.setViewName("login");

		}
		return mav;
	}

}
